package com.fs.web;

import com.alibaba.fastjson.JSONObject;
import com.fs.pojo.Discusstion;
import com.fs.service.DiscusstionService;
import com.fs.utils.BeanFactories;
import com.fs.utils.JsonData;
import com.fs.utils.ResponseJSONUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/discusstion/*")
public class DiscusstionServlet extends HttpServlet {

    private DiscusstionService discusstionService = BeanFactories.getBean(DiscusstionService.class);
    private HttpServletRequest req;
    private HttpServletResponse resp;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.req = request;
        this.resp = response;

        switch (req.getPathInfo()) {
            case "/getAllDiscusstionBelongClass": getAllDiscusstionBelongClass();break;
            case "/pulishDiscusstion": pulishDiscusstion();break;
            case "/getDiscusstionById": getDiscusstionById();break;
        }

    }

    /**
     * 根据id获取讨论主题
     */
    private void getDiscusstionById() throws IOException {
        String id = req.getParameter("id");

        Discusstion discusstion = discusstionService.queryById(id);

        ResponseJSONUtil.responseJSON(JsonData.buildSuccess(discusstion),resp);
    }

    /**
     * 发布讨论主题
     * @throws IOException
     */
    private void pulishDiscusstion() throws IOException {


        Discusstion discusstion = JSONObject.parseObject(IOUtils.toString(req.getInputStream(), "utf-8"), Discusstion.class);

        boolean b = discusstionService.pulishDiscusstion(discusstion);

        resp.getWriter().print(JSONObject.toJSONString(b?JsonData.buildSuccess(null):JsonData.buildError("服务器繁忙，发布失败！")));

    }


    /**
     * 获取某个班级下所有讨论主题
     * @throws IOException
     */
    private void getAllDiscusstionBelongClass() throws IOException {

        String classId = req.getParameter("classId");

        JsonData jsonData = JsonData.buildSuccess(discusstionService.getAllDiscusstionByClassId(classId));

        resp.getWriter().print(JSONObject.toJSONString(jsonData));

    }


}
